简体   繁体   中英

How can I add attributes to html code inside of a javascript variable?

Through the following html and js code

<!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

h1 tag, img tag etc

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 ? 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);

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