Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store HTML-Markup in the ID-Attribute?

I need to show for every 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 the later view. Now I am storing it in the 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 a simple way to reach this goal?

like image 869
user1462148 Avatar asked Dec 08 '22 23:12

user1462148


1 Answers

The id attribute is one of the least appropriate places for this (must be unique, cannot contain all characters). Use a data- attribute (introduced in HTML5 but also works in old browsers and without using a HTML5 doctype) instead:

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

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

In any case, you need to ensure that nothing breaks when inserting dynamic data in the attribute. Use htmlspecialchars() for this purpose:

$desc = '<p style="color: red">some <span>data</span></p>';
echo '<a href="#" data-desc="' . htmlspecialchars($desc) . '">' . $key . '</a>';
like image 125
ThiefMaster Avatar answered Dec 27 '22 05:12

ThiefMaster