向所有 html 标记添加属性


Adding attributes to all html tags

我想为所有标签添加id="draggable"属性。

例如-

<img src="http://sample.jpg">应更改为<img src="http://sample.jpg" id="draggable" >

<p>abcd</p>应更改为<p id="draggable">abcd</p>

这应该适用于除<HTML><HEAD><script><style>之外的所有标记

有什么建议吗?

使用 class 而不是 Ids

var elems = document.body.getElementsByTagName("*");
elems.setAttribute("class","draggable");

ID(s):每个元素只能有一个 ID每个页面只能有一个具有该 ID 的元素啪:可以在一个元素上使用多个类。您可以对多个元素使用相同的类

向所有 HTML 元素添加相同的id不是一个好方法。最好使用相同的类名。动态地,如果你想为所有元素添加相同的类,你可以做如下的事情

$('#parent').find('*').addClass('draggable');

http://jsfiddle.net/663m8qyd/

<div id='parent'>
    <p>ABC</p>
    <img src='http://www.w3schools.com/tags/smiley.gif' alt="Smiley face"/>
    <div id='child'>
        <div id='child1'>test1</div>
        <div id='child2'>test2</div>
    </div>
</div>

要将类添加到div 中的所有元素draggable parent请找到每个元素并添加相应的类。希望对您有所帮助!