如何在javascript变量中添加属性到html代码?

时间:2018-03-04 03:43:12

标签: javascript jquery html

通过以下html和js代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>
var get = $(".parent").html();
// Now I want to add some properties to div with "hello-world-2" class in html code of get variable
</script>
</head>
<body>
<div class="parent">
<div class="hello-world">
            <div class="hello-world-2">
           <h1 class="hello-world-3" style="padding-top:10px;">simple</h1>
            </div>
            <div class="hello-world-4">
            </div>
        </div>
</div>
</body>
</html>

这里我想在div中添加一些属性(如id)或在div中添加另一个div,使用类“hello-world-2”或添加一些cutom标签,例如

  

h1标签,img标签等

现在我在“get”变量中的html里面有div的代码我想在div中添加一个id而不是原始代码的“hello-world-2”类但是在get变量中的hmtl代码是否可能?感谢

1 个答案:

答案 0 :(得分:0)

这应该有效:

var e1 = document.getElementById('someId').id = 'otherId';
var e2document.getElementsByClassName('hello-world-2')[0].id = 'someId';

var newElement = document.createElement('div');
newElement.id = 'someId';
newElement.classList.add('someClass');
newElement.setAttribute('custom-attr', 'ca');

var newElement2 = document.createElement('h1');
newElement2.innerHTML = 'HEADER';

e1.appendChild(newElement);
e2.appendChild(newElement2);
相关问题