I have several divs as follows in my HTML code:
<div>#558C89</div>
and I want the background of the every div to have the value it holds. I came up with a script that does that, but only when div is clicked:
$(document).ready(function() {
$(document).on('click', 'div', function() {
$(this).css('background-color', $(this).text());
});
});
I'm total beginner in JavaScript and jQuery and I'm not sure if it is even the correct approach. I want those divs to have background colors set already when the page is loaded.
Use .each()
to iterate through each <div>
and use .text()
to extract the hex color code.
$(document).ready(function () {
$('div').each(function () {
$(this).css('background-color', $(this).text());
})
});
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.