Hello I have this code using HTML
<div class="abc">
<div class="12" id="hour"></div>
</div>
And I want to use javascript like this :
$('#hour').empty();
$('#hour').text(begin+ " \n "+end);
The problem is that I have no a new line for the variable end...
Do you have any ideas to solve this problem ?
Thank you !
Since you are adding that context in a HTML page inside a <div>, suggested way is to use html() function instead of text(). Then, you can use <br/> to add a new line. So, when this entire content is rendered as a HTML, then <br/> will add a new line. This also defines the difference between text() and html() function.
var begin = 'begin';
var end = 'end';
$('#hour').empty();
$('#hour').html(begin + "<br/> " + end);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="abc">
<div class="12" id="hour"></div>
</div>
Use html() instead of text() and <br> instead of \n
$('#hour').empty();
$('#hour').html('begin'+ "<br>"+'end');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="abc">
<div class="12" id="hour"></div>
</div>
Related
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 :)
I need to parse my website and save new version to variable.
For example i have code like this:
<body>
<div data-newname="test"></div>
<div data-newname="test2"></div>
</body>
so the new code should be:
<body>
{{Start:test}}{{End::test}}
{{Start:test2}}{{End::test2}}
</body>
I was want to use replacewiths method but this is not gonna help me :( maybe regular expression?
You are searching for replaceWith()
UPDATE: Reverse order replace the innermost first
$($('[data-newname]').get().reverse()).replaceWith(function() {
let data = $(this).data('newname')
return `{{Start:${data}}}${$(this).html()}{{End::${data}}}`
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-newname="test1">
Test1
<div data-newname="test2">Test2</div>
</div>
<div data-newname="test3">Test3</div>
You could use jQuery replaceWith() to re-wrap the elements.
Because overwriting the HTML of the outer elements will drop the nested elements from the collection, I've wrapped it in a while to ensure that the nested ones get updated as well.
while ($("[data-newname]").length) {
$("[data-newname]").replaceWith(function() {
let data = $(this).data("newname");
return `{{Start:${data}}}${$(this).html()}{{End::${data}}}`
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div data-newname="test">
<div data-newname="nested">Nested</div>
</div>
<div data-newname="test2">Test2</div>
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());
In a div with two classes, the first inner div
<div class="datacheck">
<div class="classic_div_data customdataid_305">
some values come here
</div>
<div class="optiondiv">
</div>
</div>
I need to get a substring (here the number 305) from the second class(customdataid_305) of the first inner div. For this need to get the classes.
I wrote in jquery and succeed
var xyz= $($(".datacheck").find("div")[0]).attr("class").split(" ")[1]
from which I gets the class.
Is there any simpler approach for this.
I am searching for something like this $(element).class() probably returns an array of classes
There's nothing that gives you an array of classes, although the native DOM classList is close. But I don't think classList will make things much simpler.
I'd do this:
var xyz = $(".datacheck .classic_div_data").attr("class").match(/\bcustomdataid_(\d+)\b/);
xyz = xyz && xyz[1];
The regex extracts the numeric portion of the class, without being fragile (sensitive to whether the class is the first or second in the list of classes, for instance).
Example:
var xyz = $(".datacheck .classic_div_data").attr("class").match(/\bcustomdataid_(\d+)\b/);
xyz = xyz && xyz[1];
console.log("xyz = '" + xyz + "'");
<div class="datacheck">
<div class="classic_div_data customdataid_305">
some values come here
</div>
<div class="optiondiv">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
If you can change the HTML, though, I wouldn't use a class for this at all, I'd us a data-* attribute instead:
<div class="classic_div_data" data-custom-id="305">
then
var xyz = $(".datacheck [data-custom-id]").attr("data-custom-id");
Example:
var xyz = $(".datacheck [data-custom-id]").attr("data-custom-id");
console.log("xyz = '" + xyz + "'");
<div class="datacheck">
<div class="classic_div_data" data-custom-id="305">
some values come here
</div>
<div class="optiondiv">
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
One of the major problems you have with your current design is that if the order of the classes changes, or someone adds another class, your logic breaks. You're also getting a DOMElement from a jQuery object which you turn back in to a jQuery object again.
It would be a much better approach to use data-* attributes to store your custom data, like this:
$('.classic_div_data').click(function() {
console.log($(this).data('customdataid'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="datacheck">
<div class="classic_div_data" data-customdataid="305">
some values come here
</div>
<div class="optiondiv"></div>
</div>
<div class="datacheck">
<div class="classic_div_data" data-customdataid="205">
some more values come here
</div>
<div class="optiondiv"></div>
</div>
You can get the nth class easily from the classList of element object,
var x = $(".datacheck").find("div").get(0);
var nthClass = x.classList[1]
var res = nthClass.replace("customdataid_", "");
console.log(res); //305
You can use regex in .match() to finding last digit in class.
var digit = $(".datacheck > :first").attr("class").match(/[\d]+$/g)[0];
console.log(digit);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="datacheck">
<div class="classic_div_data customdataid_305">some values come here</div>
<div class="optiondiv"></div>
</div>
I have the following HTML code within the body:
<div id="hidden">
</div>
<div id="mainContianer">
<div id="firstChildDiv">
</div>
</div>
I am using the following code to get the child
$("div:first-child").attr('id')
But this returns "hidden" when I want it to return firstChildDiv, I have tried things like...
$("div[mainContainer ] div:first-child").attr('id')
$("div[id=mainContainer ] :first-child").attr('id')
$("#mainContainer :first-child").attr('id')
I know its a simple thing to do, but cant seem to see where I am going wrong...
Thanks
Your last selector
$("#mainContainer :first-child").attr('id')
works fine, if you correct the typo in the HTML (see this fiddle). It says mainContianer instead of mainContainer.
But, anyway, why don't you select simply by the id, if that element has an id?
$( '#firstChildDiv' )
$('#mainContainer > div:first-child').attr('id');
Try this,
$("#mainContianer:first-child").attr("id")
Check there is no space before ':'
Actually, you have a typo there in your html
<div id="mainContianer">
should be
<div id="mainContainer">
Then you can do
$("#mainContainer div:first-child").prop('id')
This uses prop rather than attr, which is slower and old jQuery Syntax
This is working for me....
$(document).ready(function(){
var a =$("#mainContainer div:first-child").attr('id');
alert(a);
});
this all return you first child of parent--in your case replace parent by mainContianer
$('#parent').children(":first")
$('#parent').children(":first-child")
$( $('#parent').children()[0] )
$('#parent').find(":first")
$('#parent').find(":nth-child(1)")
try - Child Selector (“parent > child”)
$("div > div").attr('id')
also try out
$("div div:first-child")
<html>
<head>
<script>
function getDiv(){
alert("answer = "+$('#mainContianer div:first-child').attr('id'));
}
</script>
</head>
<body>
<div id="hidden"></div>
<div id="mainContianer">
<div id="firstChildDiv">
</div>
</div>
<button onclick="getDiv()">click</button>
</body>
<html>
SCRIPT
<script language="JavaScript">
jQuery(document).ready(function($) {
$("#MY_BUTTON").click(function(event) {
$("div#PARENT_DIV").find("#CHILD_DIV").hide();
});
});
</script>
HTML CODE
<div id="PARENT_DIV">
<h1 class="Heading">MY HTML PAGE TEST</h1>
<br />
<div id="CHILD_DIV">THIS IS MY CHILD DIV</div>
</div>
<div class="MY_BUTTONS">
<a class="MySubmitButton" id="MY_BUTTON">
<span>Test it!</span>
</a>
</div>
for now in 2020 with jquery it can be like:
function myClickOnDiv(divPrm) {
let div=$(divPrm);
let targetElement=div.find('#my_id')
}
if say you div looks like this:
<div onclick=myClickOnDiv(this)><label id="my_id"></label></div>