get parent divtext with jQuery - javascript

In the following markup, I want to select the text inside the .title but exclude the text which is inside the .button.
<span class="title">
Title Text
<span class="button">Button</span>
</span>
I am trying following code but it selects the .button text also. How can I exclude that without changing the HTML.
$('.title').on('click', '.button', function() {
var item = $(this).parent();
var title = item.text();
alert(title);
});

You need to retrieve value of the textNode. Try this:
$('.title').on('click', '.button', function() {
var $item = $(this).parent();
var title = $item.contents().get(0).nodeValue;
alert(title);
});
Working fiddle

Try this,
$('.title').on('click', '.button', function() {
var $item = $(this).parent();
var title = $item.contents().get(0).nodeValue;
alert(title);
});
Working Demo

Yet another way, using the built-in previousSibling property (which includes text nodes as well) [just for information sharing].
$('.title').on('click', '.button', function() {
alert(this.previousSibling.nodeValue);
// trim the above as it can contain newlines, spaces, etc. as in the source
});

You can clone the element, and remove the children. Then get the text of the cloned element.
$('.title').on('click', '.button', function() {
var title = $(this).parent().clone().children().remove().end().text();
alert(title);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="title">
Title Text
<span class="button">Button</span>
</span>

you can replace the text retrived from the button with '' in the parents text
http://jsfiddle.net/94u3rf6b/
$('.title').on('click', '.button', function() {
var item = $(this).parent();
var title = item.text().replace($(this).text(),'');
alert(title);
});

Related

Replace only part of text in jQuery function

I'm using this solution for replace a list of emojies:
(function($){
var emojies = ["smile", "smiley", "grin", "joy"];
var emojiRegex = new RegExp(":("+ emojies.join("|") +"):","g");
$.fn.toEmoji = function(){
return this.each(function() {
this.innerHTML = this.innerText.replace(emojiRegex,function(fullmatch,match){
return '<span class="emoji '+match.toLowerCase()+'"></span>';
});
});
};
})(jQuery);
//And use like
$(document).ready(function(){
$(".content div").toEmoji();
});
But this replace all the content div (this.innerHTML...), however, there is no way I do it and just replace the :emoji: and not all the text?
Because, if the text has a break line, for ex:
Hi!
How are you?
Will replace for:
Hi! How are you?
In addition to other problems... So, how to do?
The problem is you are reading from the DIV as innerText which will not include the HTML tags like <br/>. Instead, you can read from the DIV with innerHTML like so:
$.fn.toEmoji = function(){
return this.each(function() {
this.innerHTML = this.innerHTML.replace(emojiRegex,function(fullmatch,match){
return '<span class="emoji '+match.toLowerCase()+'"></span>';
});
});
};
Note this.innerHTML.replace instead of this.innerText.replace!
JSFiddle: http://jsfiddle.net/ybj7gpn6/ (inspect HTML after clicking button to see spans are present -- looks like blank space)

Press a unique button do the actions

So as I started using JavaScript and jQuery, I have a question with unique div.
Is is possible in the JavaScript to make a unique div name then do the action onclick?
http://jsfiddle.net/agmr2ytd/4/
Example HTML:
<div id="favoriteXBSbQG6fNlObroDG4ML2l9VRO/yNpvIFxL0Qjr6bP2A=">
Me
</div>
<div id="favoriteakkbN3eo8h0Q7S4ouHqMX7cU9vNLNKw3llO/PK0e9qI=">
Me 2
</div>
JavaScript:
$(function() {
$('.favorite').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
$('#favorite'+verify).hide();
});
});
When I press a first a from div I wanna get the id value as a alert and hide it.
You need to set class = favorite to your divs, then this is working:
DEMO
jQuery / javascript:
$(function() {
$('.favorite').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
var tohide = document.getElementById(verify);
tohide.style.display = 'none';
});
});
HTML:
<div id="favoriteXBSbQG6fNlObroDG4ML2l9VRO/yNpvIFxL0Qjr6bP2A=" class="favorite">
Me
</div>
<div id="favoriteakkbN3eo8h0Q7S4ouHqMX7cU9vNLNKw3llO/PK0e9qI=" class="favorite">
Me 2
</div>
Your selector is wrong, for attributes ^= means "attribute value starts with":
$(function() {
$('[id^=favorite] a').click(function() {
var element = $(this);
var verify = element.attr("id");
alert(verify);
$('#favorite'+verify.replace(/([ #;?%&,.+*~\':"!^$[\]()=>|\/#])/g,'\\$1')).hide();
});
});
Example Fiddle <-
Your ID has to be escaped, used this answer for solution.

jQuery show delete display attr

I'm using jQuery hide and show function but I have a problem with the show one.
My javascript code is:
function toggle_visibility(idContent, idLien, question) {
var c = document.getElementById(idContent);
var l = document.getElementById(idLien);
var q = question;
if(c.style.display == 'block') {
$("#" + idContent).hide("blind") ;
l.innerHTML = '<h4><i class=\"icone-rouge icon-right-open-big\"></i>'+ q +'</h4>' ;
}
else {
$("#" + idContent).show("blind") ;
l.innerHTML = '<h4><i class=\"icone-rouge icon-down-open-big\"></i>'+ q +'</h4>' ;
}
}
The problem is that it doesn't work for the hide part when the div is hidden at the load of the page (with display='none'). I can display the block but then I cannot hide it.
I noticed that when I show a content, jQuery delete the display attr in my html style... Maybe there is a link.
Here a link for example : http://jsfiddle.net/29c4D/2/
Thank you.
DescampsAu, since you are using jQuery I rewrote your code to take full advantage of the powerful library. You can see the example in this fiddle.
Let jQuery do the heavy lifting of checking whether an element is hidden or not by making use of either the .toggle() or .slideToggle() methods.
Remove all of the onClick() code within your spans and use this jQuery instead:
jQuery
$(document).ready( function() {
//After the page has loaded, let jQuery know where all of the spans are.
var toggleThis = $(".toggleMe");
//Whenever you click one of the spans do this function.
toggleThis.click( function() {
//Register the span you clicked and the next div that holds the hidden stuffs.
var el = $(this),
nextDiv = el.next(".toggleMeDiv");
//Check if the span's partner div is hidden or showing by checking its css "display" value.
if(nextDiv.css("display") == "block") {
//Change the text of the span to be its title attribute plus whether its partner is showing or hidden.
el.html(el.attr("title")+" hidden");
} else {
el.text(el.attr("title")+" shown");
}
//Let jQuery toggle the partner's visibility.
nextDiv.slideToggle();
});
});
HTML
<span class="toggleMe" title="Quest 1">Quest 1</span>
<div class="toggleMeDiv">Boubou1</div>
<span class="toggleMe" title="Quest 2">Quest 2</span>
<div class="toggleMeDiv">Boubou2</div>
Making this too hard on yourself.
HTML
<span class="toggle" id="lien1" data-original-text="Quest 1">Quest 1</span>
<div id="content1">Boubou1</div>
<span class="toggle" id="lien2" data-original-text="Quest 1">Quest 2</span>
<div id="content2">Boubou2</div>
JS
$(document).ready( function () {
$('.toggle').on('click', function() {
$(this).next('div').toggle('blind', textToggle); // or slideToggle();
});
function textToggle() {
var $target = $(this).prev('span'); // "this" is the div that was toggled.
var originalText = $target.attr('data-original-text');
if ( $(this).is(':visible') ) {
$target.text( originalText + ' open' );
} else {
$target.text( originalText + ' closed' );
}
}
});
A fiddle: http://jsfiddle.net/29c4D/7/
EDIT to include label + effect.

How to change text except its span

How can we change the text data from except span text?
<h2 id="nameUser" >Muhammed <span> mobile :989 531 9991</span></h2>
Is there any solution to change h2 except span?
.contents() returns a collection of nodes, including text nodes. So in your case this would work:
$('#nameUser').contents()​​​​​​​​[0].nodeValue = 'Another name';​​
If you want to get every node except the SPAN, try:
$('#nameUser').contents().filter(function() {
return this.nodeName != 'SPAN';
}).​each(function(i) {
// modify each text node
this.nodeValue = 'name '+i;
});​​​​​
DEMO: http://jsfiddle.net/Vks82/
Search for the first textnode in childNodes of the h2 element. Change the value of the textnode.
var element = document.getElementById('nameUser');
element.childNodes[0].nodeValue = 'New String';
..should work. Only for this example, because the first childnode is the textnode you want, you don't have to search for it. Otherwise you do..
This example may help you to change father element without changing child elements:
var content= $('#nameUser').children();
$('#nameUser').text('Altered Text').append(content);​
$('#nameUser').contents().each(function() {
if (this.nodeType == 3)
this.data = "The text you want here";
});​
Live DEMO
You can do it by saving the children first here is a codepen of it working.
http://codepen.io/beckje01/pen/sGLot
var h2 = $('#nameUser');
var elmsToSave = h2.children();
h2.empty();
h2.text('bob');
h2.append(elmsToSave);
As pointed out in the comments this will only work if the text to change is first.
This will work not only for span but also for any other element which you want the text without the text of it's children.
$("#nameUser")
.clone()
.children()
.remove()
.end()
.text();
For change the text I've create a simple jQuery function:
replaceTextWith = function($element, $replacement){
$oldText = $element.clone().children().remove().end().text();
$element.text($element.text().replace($oldText, $replacement));
}
replaceTextWith($("#nameUser"), "Bruno"); //usage
Here's a live example working on fiddle
try this ...
<h2 id="nameUser" >Muhammed <span id="nameUserSpan"> mobile :989 531 9991</span></h2>
<script>
$(document).ready(function() {
var inspan= $("#nameUserSpan").html();
var newuser='New User';
$("#nameUser").html('');
$("#nameUser").html(newuser + '<span id="nameUserSpan">' + inspan + '</span>');
});
</script>

How to reference an id with brackets in jQuery

I'm painfully new to jQuery and I need to grab the value on change of a text input box with an id of id[2][t] and display that text in a div to be styled later on (also styled with jQuery).
This is the input box code:
<input id="id[2][t]" name="id[2][t]" maxlength="20" type="text">
This is the div I am trying to display it in:
<div id="textpreview"></div>
This is what I have tried, among other variation with no success:
$(document).ready(function() {
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').text();
$("#textpreview").val(txtval);
});
});
I know the brackets are a problem but they need to remain for other reasons.
Any ideas?
$( document.getElementById( "id[2][t]" ) ).change( function(){
$( "#textpreview" ).text( this.value );
} );
You might consider revising your IDs (though I'm guessing they might be auto-generated). According to this question your IDs are invalid against the spec
Use the attribute selector instead:
var sel = $("[id='id[2][t]']");
sel.change(function() {
$("#textpreview").val(sel.text());
});
Plain Old JavaScript:
var elem = document.getElementById('id[2][t]');
elem.onchange = function()
{
var elem = document.getElementById('textpreview');
elem.removeChild(elem.firstChild)
elem.appendChild(document.createTextNode(this.value));
}
Ahhh... now doesn't that feel better?
You have val and text backwards. Swap them:
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = $('#id\\[2\\]\\[t\\]').val();
$("#textpreview").text(txtval);
});
val is used to get the value of the textbox. text to set the text within the div.
You can further simplify the code by using this instead of re-querying the element.
$('#id\\[2\\]\\[t\\]').change(function() {
var txtval = this.value;
$("#textpreview").text(txtval);
});
You can try using the attribute selector instead of the id selector.
$('[id="id[2][t]"]')

Categories

Resources