admin管理员组文章数量:1296508
I have a string of attributes written in valid html, and I want to put those attributes on an actual html element (not a html string of an element).
For example, I have the string of attributes in the sensibly named attributesStr
variable, and I want to add those attributes to the #htmlElement
div.
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
The HTML element!
</div>
I have a string of attributes written in valid html, and I want to put those attributes on an actual html element (not a html string of an element).
For example, I have the string of attributes in the sensibly named attributesStr
variable, and I want to add those attributes to the #htmlElement
div.
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
<div id="htmlElement">
The HTML element!
</div>
After the JQuery / JavaScript code is run, #htmlElement
should look like:
<div id="htmlElement" class='regularClass' title='Title... with spaces!' style='color: red; font-weight: bold;' data-attributenovalue>
The HTML element!
</div>
How can I do this in JavaScript or Jquery?
First attempt: I was thinking I could do this by .split()
ing attributesStr
on spaces, and then splitting each individual attribute key value pair on the =
, and then iterating that array and adding each key value pair with JQuery's .prop()
or .attr()
, but this wouldn't work for two reasons:
- It would fail on the
style
andtitle
attributes because they have spaces. - It might fail on the attributes with no value.
-
attributesStr.match(/[^\s=]+(=['][^']*['])?/g)
this will get you the first split – tallberg Commented Oct 4, 2017 at 13:17 - 4 You're making this harder than it needs to be by hacking around the pre-built string. Can you not apply the styles at the point you build that string? Or even create an object with those values to be applied later? – Rory McCrossan Commented Oct 4, 2017 at 13:17
- @RoryMcCrossan I've already found a different solution to my original problem, I was just curious if there was a way to do this in JS/JQuery :) – Ethan Commented Oct 4, 2017 at 13:19
- @tallberg Please feel free to post an answer if you think you have a solution that works :) – Ethan Commented Oct 4, 2017 at 13:20
- 1 Sure, there's lots of ways to do anything, but most of them aren't the best way for a variety of reasons. – Rory McCrossan Commented Oct 4, 2017 at 13:20
6 Answers
Reset to default 5Take the attributesStr
and insert it into the existing outerHTML
. To achieve this, you need to reconstruct the node by removing the existing tag, injecting the string, and putting back the rest of the html.
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
var element = document.getElementById('htmlElement');
var tag = element.tagName;
element.outerHTML = '<' + tag + attributesStr + element.outerHTML.substring(tag.length + 1);
<div id="htmlElement">
The HTML element!
</div>
You can use .attr() to do this in jquery. Here is the working snippet.
click here for attr() usage
$(document).ready(function(){
$("#htmlElement").attr("class", "regularClass");
$("#htmlElement").attr("title", "Title... with spaces!");
$("#htmlElement").attr("style", "color: red; font-weight: bold");
$("#htmlElement").attr("data-attributenovalue",true);
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
The HTML element!
</div>
Try this:
var dummHTML = $("<div "+attributesStr+"></div>");
$.each(dummHTML[0].attributes, function(i,v){
$('#htmlElement').attr(v.nodeName,v.nodeValue);
});
Maybe not the best option but if its required to use the full string:
The idea is: take the content of the element, then remove it and create it again with the new attributes:
var attributesStr = "";
attributesStr += " class='regularClass'"; // Needs to handle key value attributes.
attributesStr += " title='Title... with spaces!'"; // And attributes with spaces.
attributesStr += " style='color: red; font-weight: bold;'"; // And style with multiple properties.
attributesStr += " data-attributenovalue"; // And attributes with no value.
// Your special code to add the attributes to `#htmlElement` goes here.
var $innerHTML = $("#htmlElement").html()
$("#htmlElement").remove()
var $newElement = "<div id='htmlElement' " + attributesStr + ">" + $innerHTML + "</div>"
$("body").after($newElement)
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
The HTML element!
</div>
Why not separating your string with ','
var attributesStr = "";
attributesStr = attributesStr + " class='regularClass'," ; // Needs to handle key value attributes.
attributesStr = attributesStr +" title='Title... with spaces!',"; // And attributes with spaces.
attributesStr = attributesStr +" style='color: red; font-weight: bold;',"; // And style with multiple properties.
attributesStr = attributesStr +" data-attributenovalue,"; // And attributes with no value.
var array = attributesStr.split(',');
array.forEach(function(item){
property = item.split('=');
$('#htmlElement').attr(property[0].trim());
if(property[1]) $('#htmlElement').attr(property[0].trim(), property[1].trim());
});
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="htmlElement">
The HTML element!
</div>
This will get you the first split
attributesStr.match(/[^\s=]+(=['][^']*['])?/g)
result:
["class='regularClass'", "title='Title... with spaces!'", "style='color: red; font-weight: bold;'", "data-attributenovalue"]
Then in an foreach
you can handle the attrs as you suggested.
本文标签: javascriptAdd a string of html attributes to a html elementStack Overflow
版权声明:本文标题:javascript - Add a string of html attributes to a html element - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741611173a2388266.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论