How to save HTML markup in an id attribute?

I need to show for each link dynamically some text with Java Script (jQuery). The problem is that the text is also formatted as HTML, so this causes some problems in a later presentation. Now I save it in an ID attribute, this works, but only without embedded HTML in it.

<?php ... $desc = '<p style="color: red">some <span>data</span></p>'; echo '<a href="#" id="' . $desc . '">' . $key . '</a>'; ?> 

Ajax requests are not allowed. Is there an easy way to achieve this?

+4
source share
2 answers

The id attribute is one of the least suitable places for this (it must be unique, cannot contain all characters). Use the data- attribute (introduced in HTML5, but also working in older browsers and without using an HTML document):

 <a href="#" data-desc="...."> 

If you use jQuery, you can access it via .data('desc') , in normal JavaScript the most portable way is .getAttribute('data-desc') . If you do not need to support older browsers, you can access the value using the .dataset.desc property.

In any case, you need to make sure that when you insert dynamic data into the attribute, nothing will break. Use htmlspecialchars() for this purpose:

 $desc = '<p style="color: red">some <span>data</span></p>'; echo '<a href="#" data-desc="' . htmlspecialchars($desc) . '">' . $key . '</a>'; 
+13
source

Other comments are absolutely true. Do not do that. It is impractical to put in the id attribute anything but an identifier of some type.

Having said that, I decided that I would let you know why your code fails. You must use htmlspecialchars() in your data before trying to use it on your own. This way, HTML will not be interpreted as HTML ... all HTML objects will be converted to, so your attribute value is interpreted as text. < becomes &lt; , > becomes &gt; etc. If you later pull the value out (using jQuery or something else), you will get the text of your choice.

+1
source

All Articles