How to wrap in 2 elements with jQuery? - javascript

I want to make the following code:
<h2>TEXTz</h2>
<p>ARTICLE</p>
<h2>TEXTx</h2>
<p>ARTICLE</p>
Look like this:
<div class="highlight">
<h2>TEXTz</h2>
<p>ARTICLE</p>
</div>
<h2>TEXTx</h2>
<p>ARTICLE</p>
But I have to use: contains for find h2 text and add wrap before h2 and after p.
My failed code:
$.extend($.expr[':'],{containsExact: function(a,i,m){return $.trim(a.innerHTML.toLowerCase()) === m[3].toLowerCase();}});
var byItem = "TEXTz"
var ItemTitle = $("h2:containsExact(" + byItem +")").text();
var ItemDes = $("h2:containsExact(" + byItem +")").next("p").text();
$("h2:containsExact(" + byItem +")").html('<section class="highlightitem"><h2>' + ItemTitle + '</h2><p>' + ItemDes + '</p></div>');
http://jsfiddle.net/NDUzW/

The method .add() allows adding elements to a jquery object.
Then you can use .wrapAll() to wrape a set of elements in jQuery.
var $h2 = $("h2:containsExact(" + byItem +")");
if ($h2.length) {
$h2.add( $h2.next('p') )
.wrapAll( $('<div>').addClass('highlight') );
}
Working example on jsfiddle

Simply use the jQuery functions:
var byItem = "TEXTz"
$("h2")
.filter(
function() {
if ($(this).html() == byItem) {
return true;
}
return false;
}
)
.next("p")
.andSelf()
.wrapAll($("<section>")
.addClass("highlightitem")
);
Example

Related

Need to escape two colons in jquery selector

I need to select an HTML element using JQuery, and the selector that I'm using has two colons. I'm trying to escape these colons.
<div value="some::value_test"></div>
function escapeColon(selector) {
return selector.replace(/::/, '\\\\:\\\\:');
}
var stringToEscape = "some::value_test";
var selector = $("[value|='" + escapeColon(stringToEscape) + "']");
My code above isn't working for some reason. I can get it to work fine when there is one ':' in the selector, but not when there are two.
jQuery has the method built in. escapeSelector
var stringToEscape = "some::value";
var elem = $("[value|='" + $.escapeSelector(stringToEscape) + "']");
console.log(elem.attr("value"));
stringToEscape = "some::value_test";
elem = $("[value|='" + $.escapeSelector(stringToEscape) + "']");
console.log(elem.attr("value"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div value="some::value"></div>
<div value="some::value_test"></div>
With your code, you are escaping the \ too many times.
function escapeColon(selector) {
return selector.replace(/:/g, '\\:');
}
var stringToEscape = "some::value";
var elem = $("[value|='" + escapeColon(stringToEscape) + "']");
console.log(elem);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div value="some::value"></div>

How to wrap each iteration in $each loop?

I'm looping through a JSON array using the jQuery $each function. I think i'm being incredibly thick here, but I'd like to wrap the 3 elements in a container div on each iteration. Please advise?
success: function(data) {
var access = data.query.results.json.data;
$.each(access, function(index, value) {
var ob = value;
$(".front-page .main .object").append('<img class="post-image" src="' + ob.images.standard_resolution.url + '">');
$(".front-page .main .object").append('<div class="post-caption">' + ob.caption.text + '"</div>');
$(".front-page .main .object").append('<div class="post-tags">' + ob.tags + '"</div>');
});
},
To do that you can create the wrapper object, append the three items to it, then append the wrapper to the target, something like this:
var access = data.query.results.json.data.forEach(function(obj) {
var $wrapper = $('<div />').appendTo('.front-page .main .object');
$wrapper.append(`<img class="post-image" src="${obj.images.standard_resolution.url}" />
<div class="post-caption">${obj.caption.text}</div>
<div class="post-tags">${obj.tags}</div>`);
});

jquery dynamically split string and wrap into class

I'm trying to split the div's text and add class to the second string. But no luck :(
Here's the code:
<div class="graphTooltipText">925 11:45pm</div>
This is not working:
var str = $( ".graphTooltipText" ).html();
var splitter = str.split(' ')[1];
$(splitter).wrap('<div class="time" />');
Any help is appreciated.
You need to wrap it and then update the original element, so try
$('.graphTooltipText').html(function (i, html) {
return html.replace(/\s(.*$)/, ' <div class="time">$1</div>')
});
Demo: Fiddle
http://jsfiddle.net/kJm8Q/1/
This simply wraps the item, and spits out the 2nd array element:
$(".graphTooltipText").wrap(function() {
$(this).html("<div class='time'>" + $( this ).text().split(" ")[1] + "</div>");
});
Try This:
var str = $(".graphTooltipText").html(function (_, html) {
return html.replace(html.split(' ')[1], '<div class="time" >' + html.split(' ')[1] + '</div>');
});
you can use it too:
var str = $(".graphTooltipText").text();
var splitter = str.split(' ');
var timeDiv = $('<div/>', {
'class': 'time',
text: splitter[1] // put the time here
});
$(".graphTooltipText").html(splitter[0]).append(timeDiv); // update the div content
Fiddle

How to get the value of id of innerHTML?

I have created a html like this:
<body onload = callAlert();loaded()>
<ul id="thelist">
<div id = "lst"></div>
</ul>
</div>
</body>
The callAlert() is here:
function callAlert()
{
listRows = prompt("how many list row you want??");
var listText = "List Number";
for(var i = 0;i < listRows; i++)
{
if(i%2==0)
{
listText = listText +i+'<p style="background-color:#EEEEEE" id = "listNum' + i + '" onclick = itemclicked(id)>';
}
else
{
listText = listText + i+ '<p id = "listNum' + i + '" onclick = itemclicked(id)>';
}
listText = listText + i;
//document.getElementById("lst").innerHTML = listText+i+'5';
}
document.getElementById("lst").innerHTML = listText+i;
}
Inside callAlert(), I have created id runtime inside the <p> tag and at last of for loop, I have set the paragraph like this. document.getElementById("lst").innerHTML = listText+i;
Now I am confuse when listItem is clicked then how to access the value of the selected item.
I am using this:
function itemclicked(id)
{
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
But getting value as undefined.
Any help would be grateful.
try onclick = itemclicked(this.id) instead of onclick = 'itemclicked(id)'
Dude, you should really work on you CodingStyle. Also, write simple, clean code.
First, the html-code should simply look like this:
<body onload="callAlert();loaded();">
<ul id="thelist"></ul>
</body>
No div or anything like this. ul and ol shall be used in combination with li only.
Also, you should always close the html-tags in the right order. Otherwise, like in your examle, you have different nubers of opening and closing-tags. (the closing div in the 5th line of your html-example doesn't refer to a opening div-tag)...
And here comes the fixed code:
<script type="text/javascript">
function callAlert() {
var rows = prompt('Please type in the number of required rows');
var listCode = '';
for (var i = 0; i < rows; i++) {
var listID = 'list_' + i.toString();
if (i % 2 === 0) {
listCode += '<li style="background-color:#EEEEEE" id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
else {
listCode += '<li id="' + listID + '" onclick="itemClicked(this.id);">listItem# ' + i + '</li>';
}
}
document.getElementById('thelist').innerHTML = listCode;
}
function itemClicked(id) {
var pElement = document.getElementById(id).innerHTML;
alert("Clicked: " + id + '\nValue: ' + pElement);
}
</script>
You can watch a working sample in this fiddle.
The problems were:
You have to commit the id of the clicked item using this.id like #Varada already mentioned.
Before that, you have to build a working id, parsing numbers to strings using .toString()
You really did write kind of messy code. What was supposed to result wasn't a list, it was various div-containers wrapped inside a ul-tag. Oh my.
BTW: Never ever check if sth. is 0 using the ==-operator. Better always use the ===-operator. Read about the problem here
BTW++: I don't know what value you wanted to read in your itemClicked()-function. I didn't test if it would read the innerHTML but generally, you can only read information from where information was written to before. In this sample, value should be empty i guess..
Hope i didn't forget about anything. The Code works right now as you can see. If you've got any further questions, just ask.
Cheers!
You can pass only the var i and search the id after like this:
Your p constructor dymanic with passing only i
<p id = "listNum' + i + '" onclick = itemclicked(' + i + ')>
function
function itemclicked(id)
{
id='listNum'+i;
alert("clicked at :"+id);
var pElement = document.getElementById(id).value;
alert("value of this is: "+pElement);
}
is what you want?
I am not sure but shouldn't the onclick function be wrapped with double quotes like so:
You have this
onclick = itemclicked(id)>'
And it should be this
onclick = "itemclicked(id)">'
You have to modify your itemclicked function to retrieve the "value" of your p element.
function itemclicked( id ) {
alert( "clicked at :" + id );
var el = document.getElementById( id );
// depending on the browser one of these will work
var pElement = el.contentText || el.innerText;
alert( "value of this is: " + pElement );
}
demo here

Selecting textareas within div tags

feel like im coming here way too often to ask questions but yet again I am stuck. I am attempting to select a textarea and allow myself to edit the text in another textarea, which works fine using textboxs but not with textareas. Every time I click on the div container I am getting an undefined result when looking for the textarea. Below is the code.
jQuery
$(".textAreaContainer").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID ).find(':input');
alert(t.attr('id'));
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
//var textboxId = $('div.textAreaContainer').find('input[type="textArea"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" Textarea shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
t.attr('id') should be returning textbox1(or similar) but instead just returns undefined.
I have tried .find(':textarea'),.find('textarea'),.find(text,textArea),.find(':input') and quite a few others that I have found through google but all of them return undefined and I have no idea why. A demo can be found here, http://jsfiddle.net/xYwaw/. Thanks in advance for any help guys, it is appreciated.
EDIT: Below is the code for a very similar example I am using. This does what I want to do but with textboxs instead of textareas.
$('#textAdd').live('click',function() {
var newdiv = document.createElement('div');
newdiv.innerHTML = "Textbox " + textBoxCounter + " <br><div id='container" + counter + "' class='container'><li><input type='text' id='textBox" + textBoxCounter +"' name='textBox" + textBoxCounter + "'></li></div></br>";
document.getElementById("identifier").appendChild(newdiv);
textBoxCounter++
counter++;
});
$(".container").live('click','div', function(){
var divID = this.id;
if ( divID !== "" ){
var lastChar = divID.substr(divID.length - 1);
var t = $('#' + divID).find('input');
alert(divID);
t = t.clone(false);
t.attr('data-related-field-id', t.attr('id'));
alert(t.attr('id'));
t.attr('id', t.attr('id') + '_Add');
t.attr('data-add-field', 'true');
var text = document.getElementById(divID).innerHTML;
// var textboxId = $('div.container').find('input[type="text"]')[lastChar].id;
$('div#placeholder input[type="button"]').hide();
var text = "<p>Please fill out what " + t.attr('id') +" textbox shall contain</p>";
if ( $('#' + t.attr('id')).length == 0 ) {
$('div#placeholder').html(t);
$('div#placeholder').prepend(text);
}
}
else{
}
});
First up remove the second parameter, 'div', from the first line:
$(".textAreaContainer").live('click','div', function(){
...to make it:
$(".textAreaContainer").live('click', function(){
Then change:
var t = $('#' + divID ).find(':input');
...to:
var t = $(this).find(':input');
Because you already know that this is the container so there's no need to select it again by id. Also the id attributes that you're assigning to your textarea containers have a space in them, which is invalid and results in your original code trying to select the element with '#textAreaContainer 0' which actually looks for a 0 tag that is a descendant of #textAreaContainer. So fixing the code that creates the elements to remove that space in the id is both a good idea in general and an alternative way of fixing this problem.

Categories

Resources