Selection javascript


#1
<!DOCTYPE html>
<html>
<head>
<title>getElementById example</title>
<script>
function changeColor(newColor) {
var elem = document.getElementById("para1").style.color = newColor;
} 
</script>
</head>
<body>
<p>some text here</p>
<p id="para1">Some text here</p>
<div id="para1">some text here too</div>
<button onclick="changeColor('blue');">blue</button>
<button onclick="changeColor('red');">red</button>
</body>
</html>

what should i do to make only div tag highlighted??and why doesn’t it require


#2

The changeColor() function changes the color of the div element with id as para1. You have to change the id of the div to something else and then change the document.getElementById("para2").style.color = newColor;.
You can do something like this,
`

getElementById example

some text here

para1 = Some text here

para2 = some text here too

Buttons for div=para1

blue red

Buttons for div=para2

red blue ` I have added an extra parameter to the changeColor function that changes the color of the div element as given in the second parameter.

#3

id should be unique. In your case div as well as p tag has both same id. in order to highlight only div change the id of p tag from para1 to something else.


#4

i want both to get highlighted in my code but only the first tag gets highlighted in my code.


#5

If you want to highlight both better use class instead of Id. For the same , code will be:
<!DOCTYPE html> <html> <head> <title>getElementById example</title> <script> function changeColor(newColor) { var elem = document.getElementByClassName("para1").style.color = newColor; } </script> </head> <body> <p>some text here</p> <p class="para1">Some text here</p> <div class="para1">some text here too</div> <button onclick="changeColor('blue');">blue</button> <button onclick="changeColor('red');">red</button> </body> </html>