Masha
Masha

Reputation: 857

How can I add data params to an HTML string and get a string back?

I got a string like this:

var select_string = '<select><option>1</option><option>2</option></select>';

I need to add some data params to select in this string and get this string back in order to get the following:

select_string = '<select data-param1="param1" data-param2="param2"><option>1</option><option>2</option></select>';

I tried to use jQuery functions like .html() or .text() but it did not work. Like this:

select_string = $(select_string).data('param1', 'param1').html() //or .text()

Any ideas how to make it work would be helpful. Thank you.

Upvotes: 1

Views: 366

Answers (4)

agentile1990
agentile1990

Reputation: 16

You could use indexOf and substr() to split it into 2 parts, insert your new text, and put it back together again.

var first_half = select_string.substr(0, select_string.indexOf('>'));

var second_half = select_string.substr(select_string.indexOf('>'));

select_string = first_half + ' data-param1=\"param1\" data-param2=\"param2\" ' + second_half;

Upvotes: 0

meneroush
meneroush

Reputation: 69

EDIT: Titulum is right, jquery is not needed here.
But here is the working example usign jquery

var selectString = '<select><option>1</option><option>2</option></select>';
var $select = $(selectString);
$select.attr("prop_key","prop_value");
var selectChanged = $select.prop('outerHTML');

console.log(selectChanged)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Upvotes: 1

Titulum
Titulum

Reputation: 11446

You don't need jQuery for this:

const myElement = document.createElement('div');
myElement.innerHTML = "<select><option>1</option><option>2</option></select>";
const selectElement = myElement.getElementsByTagName("select")[0];
selectElement.setAttribute("data-param1", "param1");
selectElement.setAttribute("data-param2", "param2");

Upvotes: 0

T&#226;n
T&#226;n

Reputation: 1

You can use attr to add that attributes to the element

var select_string = '<select><option>1</option><option>2</option></select>';

var select = $(select_string).attr({
  'data-param1': 'param1',
  'data-param2': 'param2'
});

console.log(select.prop('outerHTML'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Since your attribute name starts with data-, if you want to get the value, you can use:

select.data('param1'); // param1
select.data('param2'); // param2

Upvotes: 6

Related Questions