Attribute and Variable (Simple) - javascript

I'm trying to use a VARIABLE as a ATTRIBUTE value...
I have :
var text = "Hello!";
and the HTML is :
<li class="pro" id="text"> ---> (I want the attribute ID to equals the TEXT variable)
How can I make this work?
Thank you
EDIT
I will be more specific in my question.
Here's what I really have :
<li class="product" name="RD-101" price="18" minimum="4" gap="4">
<a class="product-image fancybox" href="images/product_big.jpg" title="Picture 4">
<img src="images/product_2.png" alt="Preview"/>
<div class="text-overlay">
<p class="product-heading">Description</p>
Enseignes résidentielles imprimées sur 2 panneaux 4 mm 36” x 24” collés dos à dos.
</div>
</a>
<p class="product-heading">RD-101 (Simple)</p>
Ajouter au panier
<p class="product-meta">Double de pareterre 32x24</p>
<div class="product-price">18<span class="product-currency">$</span></div>
</li>
As you can see I use custom attributes that are set in my Javascript code.
I want to know how to set (for instance)...the PRICE attribute to a VARIABLE VALUE instead of the number "18" like it is right now in what I pasted up there.
I was thinking of something like -->
<li class="product" name="RD-101" price="MY_VARIABLE_HERE" minimum="4" gap="4">

Use $("li.pro").attr('id', text); with jQuery
Remember attribute name is not valid for a <li>
EDIT :
With no jQuery, this code add a price (not valid) attribute to all li elements
<ul id="my_ul_id">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>
-
var text = 'Hello';
var arr_li = document.getElementById("my_ul_id").getElementsByTagName("li");
for(var i=0 ; i<arr_li.length ; i++)
{
arr_li[i].setAttribute('price', text);
}
Last thing, we said price wasn't a valid attribute.
If you want your HTML doc to be valid, have a look here

You could use the JQuery attr method:
var theName = 'yourMom';
$('li.pro').attr('name', theName);​
http://jsfiddle.net/J798a/2/

As you've specified "javascript" rather than "jquery", you could do something along the following...
<script type="text/javascript">
var text = "Hello!";
document.getElementById("liItem").setAttribute("id",text);
</script>
<ul>
<li class="pro" id="liItem">
</ul>
Updated to reflect change of attribute from "name" to "id"

$("li.pro").attr('name', text);
you can use any name for attribute, you like

Javascript would set it with
<script type="text/javascript">
var text = "Hello!";
document.getElementById("changeMe").setAttribute("id",text);
</script>
<ul>
<li id="changeMe">
</ul>
setAttribute sets the provided attribute (first argument) to the value of the second arguement... so element.setAttribute("name", "john smith") would set the name to "john smith" and element.setAttribute("class", "math") would set the class attribute to "math".

You can also do it with javascript templating libraries.
Some examples:
Handlebars
JavascriptMVC/CanJS
a ton of others
With JavascriptMVC, for example, an ejs file containing the following line (where text is actually a JS variable) will be transformed to html:
<li class="pro" id="<%= text %>">
You may read on this here:
http://javascriptmvc.com/docs.html#!jQuery.View
Welcome to the Fantastic Infinite Javascript Framework/libraries world :)!!

Related

Get Html Code, replace parts and store in variable as string without changing the DOM Element

i have a DOM Element
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
I want to get the HTML like $('.list-item').html();
Then i want to fill parts like data-attributes and content with own variables so i can get for example this:
<div class="list-item">
<div class="name">NAME CONTENT</div>
<div class="id" data-id="123456">CONTENT</div>
Link
</div>
Then i want to store that as string in a varibale like
var htmlCode = '<div class="list-item">.....';
The tricky part here is to do that all in Javascript without changing the DOM Element. I hope for help. Thanks!
You can use .clone() to clone your div and then use .attr() to change attr from id class .
Demo Code :
var htmls = $(".list-item").clone()
$(htmls).find(".id").attr('data-id', 'somehting');
console.log($(htmls).html()) //store in variable..
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="list-item">
<div class="name"></div>
<div class="id" data-id=""></div>
Link
</div>
You can use this
<script>
var html = $('.list-item').html();
console.log(html);
var list = $('<li></li>')
$('.list-item').children().each(function(index,elem){
$(list).append($(elem).clone());
})
$(list).children().each(function(i,e) {
$(e).data("id","1234")
$(e).html("ll");
})
console.log($(list).children());
</script>
Thank you all. With your help i got this solution:
var $temp = $('.list-item').html();
var $code = temp.replace('data-id=""', 'data-id="1234"').replace('href=""', 'href="https://link.de"');
So $code is my varibale wich stores the html as string without changing the DOM Element :)

Copy HTML from element, replace text with jQuery, then append to element

I am trying to create portlets on my website which are generated when a user inputs a number and clicks a button.
I have the HTML in a script tag (that way it's invisible). I am able to clone the HTML contents of the script tag and append it to the necessary element without issue. My problem is, I cannot seem to modify the text inside the template before appending it.
This is a super simplified version of what I'd like to do. I'm just trying to get parts of it working properly before building it up more.
Here is the script tag with the template:
var p = $("#tpl_dashboard_portlet").html();
var h = document.createElement('div');
$(h).html(p);
$(h).find('div.m-portlet').data('s', s);
$(h).find('[data-key="number"]').val(s);
$(h).find('[data-key="name"]').val("TEST");
console.log(h);
console.log($(h).html());
console.log(s);
$("div.m-content").append($(h).html());
<script id="tpl_dashboard_portlet" type="text/html">
<!--begin::Portlet-->
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<!--begin::Form-->
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
<!--end::Portlet-->
</script>
I'm not sure what I'm doing wrong here. I've tried using .each as well with no luck. Both leave the value of the span tags empty.
(I've removed some of the script, but the variable s does have a value on it)
You have two issues here. Firstly, every time you call $(h) you're creating a new jQuery object from the original template HTML. As such any and all previous changes you made are lost. You need to create the jQuery object from the template HTML once, then make all changes to that object.
Secondly, the span elements you select by data-key attribute do not have value properties to change, you instead need to set their text(). Try this:
var s = 'foo';
var p = $("#tpl_dashboard_portlet").html();
var $h = $('<div />');
$h.html(p);
$h.find('div.m-portlet').data('s', s);
$h.find('[data-key="number"]').text(s);
$h.find('[data-key="name"]').text("TEST");
$("div.m-content").append($h.html());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="tpl_dashboard_portlet" type="text/html">
<div class="m-portlet">
<div class="m-portlet__head">
<div class="m-portlet__head-caption">
<div class="m-portlet__head-title">
<h3 class="m-portlet__head-text">
<span data-key="number"></span> [<span data-key="name"></span>]
</h3>
</div>
</div>
<div class="m-portlet__head-tools">
<ul class="m-portlet_nav">
<li class="m-portlet__nav-item">
<i class="la la-close"></i>
</li>
</ul>
</div>
</div>
<div class="m-portlet__body">
Found! <span data-key="number"></span> [<span data-key="name"></span>]
</div>
</div>
</script>
<div class="m-content"></div>
In my case only this is working:
var template = $('template').clone(true, true); // Copies all data and events
var $h = $('<div />');
$h.html(template);
$h.find('.input-name').attr('value', "your value here"); // Note: .val("your value here") is not working
$('.list').prepend($h.html());

How to remove an attribute from an HTML element

<ol>
<li id="ItsMyKitchen">It's My Kitchen</li>
<div id="mykitchen" hidden>
<img src="images/image1.jpg" height="200px" width="200px"/>
<ul>
<li>Pizza</li>
<li>Camorised Oinon rice</li>
<li>Jollof</li>
<li>Banku with Okor</li>
<li>Fufu</li>
<li>Spanish Omellet</li>
<li>Fried Rice with Beef</li>
<li>Steamed Rice with Curry Chicken</li>
<li>Yong Chow Fried Rice </li>
</ul>
</div>
i want to remove the "hidden" attribute from the div element that has "mykitchen" as the id. Am using this javascript code
var ItsMyKitchen1 = document.getElementById("ItsMyKitchen");
ItsMyKitchen1.onclick = function(){
document.getElementById("myKitchen").removeAttribute("hidden");
}
but it seems not to be working. any help
You've created your div with id mykitchen, but when you try to get the element by id, you're trying to select a div with id myKitchen. Try making those two match, and then your code should work as expected.
Your use of element.removeAttribute is correct, but capitalization matters for element ids!
You can try this way.
document.getElementById("mykitchen").addEventListener("load", myFunction);
function myFunction() {
document.getElementById("mykitchen").removeAttribute("hidden");
}

Use Jquery to italicize all list elements

My assignment is:
In jQuery, write a function that italicizes all list elements on the page when the client fires the function (say, from a hyperlink)
This is how I am approaching this question:
$(document).ready(function() {
$("li").click(function() {
//here I am trying to change the text because str.italicize() method didn't work
var name = $('#lis').val() + "way";
$('li').text(name);
})
});
<li id="lis">Saujan</li>
<li>Uprety</li>
<li>Saujan</li>
<li>Uprety</li>
<li>Saujan</li>
<li>Uprety</li>
<br>
<div class="in">
<li>Saujan</li>
<li>Uprety</li>
<li>Saujan</li>
<li>Uprety</li>
But it does not make the list elements italic.
How can I go about making all of the list elements on the page italic?
There is no string method named italicize. While there is a String.prototype.italics method, it is non-standard and should not be used
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/italics
One possible implementation in jQuery is to use the css method and pass in font-style as the attribute.
$("button").on("click", function() {
$("li").css({"font-style":"italic"});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li>Apples</li>
<li>Oranges</li>
<li>Mangos</li>
<li>Pineapples</li>
</ul>
<button>Italicize Fruits</button>

how to add id to pre tag from the closest li element with javascript

I want to add an ID to a pre tag from the closest li tag in which is the pre tag:
So this is what I have now:
<li id="12345">
<pre class="code">
<!-- some code goes here -->
</pre>
</li>
And it should become this:
<li id="12345">
<pre class="code" id="12345">
<!-- some code goes here -->
</pre>
</li>
solution with data-id instead of id:
$('pre').each(function(){
$(this).attr('data-id', $(this).closest('li').attr('id'));
});
The elemnts id should be unique in the dom. Try appending some string to make it unique like this:
$(document).ready(function(){
$('li').find('pre').attr('id', function(d){ return $(this).parent().attr('id')+'_pre'; });
});
You can try something like this:
(function() {
var test = document.getElementById("test");
var pre = test.getElementsByTagName("pre")[0];
pre.id = "pre_" + test.id;
console.log(pre)
})()
<div id="test">
<ul>
<li>
<pre>Test Pre</pre>
</li>
</ul>
</div>
Try this :
$(document).ready(function(){
$('li').each(function(i)
{
var id = $(this).attr('id');
$(this).find('pre').data('id',id);//for data-id
$(this).find('pre').attr('id',id);//for id
});
});
First of all, id are unique keys and cannot be repeated.
You should better add Class not id.
However, to answer your question, try the below code.
var x = document.getElementsByTagName('pre');
var y = x.parent;
x.setAttribute("id", y.id);

Categories