简体   繁体   中英

add HTML ID via DOM javascript manpulation

Is it possible to add an HTML ID via the browser console using DOM Manipulation?

For example, suppose I am dealing with the following element:

<div class="elementClass">

I can fetch via DOM with something like:

document.getElementsByClassName("elementClass");

However, is it possible to add an attribute via this type of method? If I inspect the element with chrome I can do it manually, but I am wondering if it's possible to inject that ID via JavaScript.

Thanks!

你可以做:

document.getElementsByClassName("elementClass")[0].setAttribute("id", "some ID");

Yes you can modify attributes of an object (HTMLElement) via javascript

getElementsByclassName returns an array, simply iterate through the list and set the attributes you wish.

var elements = document.getElementsByClassName("elementClass");
for(var I = 0; I < elements.length; I++)
    element[I].id = "element" + I;

Then you could access any of those elements with that class via

 var element = document.getElementById("element" + 0);  //Gets First Element 

Sure.

document.getElementsByClassName('elementClass')[0].id = 'someID';

or

document.getElementsByClassName('elementClass')[0].setAttribute('id', 'someID');

Just know that if you grab elements using getElementsByClassName then it will return an array of elements (assuming any elements with the matching class exist) so modifying the array won't give you the result you want.

setAttribute() method on the DOM element should work just fine.

HTML

<div class="elementClass">
  This is the content of elementClass
</div>

<button onclick="buttonClicked()">Click to add attribute id red to elementClass</button>

Javascript

function buttonClicked(){
 document.getElementsByClassName("elementClass")[0].setAttribute("id", "red");
}

CSS

#red {
  background-color: red;
}

PLAYGROUND

Note that manipulating the class attribute causes the browser to reflow , therefore it is worth mentioning to use setAttribute() wisely to not cause performance issue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM