[英]How can I add attributes to html code inside of a javascript variable?
Through the following html and js code 通过以下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>
Here I want to add some properties such as id to the div or adding another div inside the div with class "hello-world-2" or add some cutom tags such as 在这里,我想为div添加一些属性,例如id或在类“ hello-world-2”的div中添加另一个div或添加诸如
h1 tag, img tag etc
h1标签,img标签等
Now I have the code of div inside html in "get" variable I want to add an id to div with "hello-world-2" class not to original code but to the hmtl code in get variable is it possible ? 现在,我在“ get”变量中的html内有div的代码,我想向具有“ hello-world-2”类的div添加一个ID而不是原始代码,但要在get变量中的hmtl代码中添加ID? thanks
谢谢
This should work: 这应该工作:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.