Highlight a word's parent using jQuery? - javascript

Let's say for example that I have a webpage.
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
<li>Vestibulum auctor dapibus neque.</li>
</ul>
I want to find all instances of the word 'Lorem' and manipulate them in two ways:
Wrap it with <mark> HTML5 element
Run .addClass('look-at-me'); on its parent element.
So the resulting HTML would be
<ul>
<li class="look-at-me"><mark>Lorem</mark> ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
<li>Vestibulum auctor dapibus neque.</li>
</ul>
I've read all the comments on Highlight a word with jQuery and I've been playing around with the JS code from highlight: JavaScript text higlighting jQuery plugin but both of these deal with ONLY highlighting the word in context. I manipulated the code to wrap the word using <mark> but I'm not skilled enough with JS to achieve my #2 goal of highlighting the parent container. I'm eager to see your helpful suggestions. Thanks!
EDIT: SOLVED! http://jsfiddle.net/GB8zP/1/

$('li').each(function () {
$(this).html($(this).html().replace(/Lorem/ig, "<mark>$&</mark>"));
if ($(this).text().toLowerCase().indexOf('lorem') >= 0) $(this).addClass('look-at-me');
});
jsFiddle example

try this
$("ul li:contains('Lorem')").each(function() {
$(this).html($(this).html().replace("Lorem","<mark>Lorem</mark>"));
$(this).parent().addClass("look-at-me");
})

Here's what I came up with: http://jsfiddle.net/c24w/cZegf/
HTML
<ul id="test">
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam lorem tincidunt mauris eu Lorem risus.</li>
<li>Vestibulum auctor dapibus neque.</li>
</ul>
JS
$('li', '#test').each(function highlightElement(i, e) {
e = $(e);
e.html(e.html().replace(/lorem/gi, function handleMatch(match) {
if (!e.hasClass('look-at-me')) e.addClass('look-at-me');
return '<match>' + match + '</match>';
}));
});
CSS
.look-at-me {
background: #f00;
}
match {
background: #ff0;
}
Info
Regular expression:
/lorem/gi
↑↑
||_ case-insensitive
|_ matches multiple (global)
Match function:
handleMatch(match) - each successful regular expression match is passed to this function, where the matched text is surrounded with <match></match>. This implementation makes it easier to change the exact pattern you want to highlight, because only the regular expression requires updating. Also, the parent element of the match is highlighted accordingly, if required.

Related

Put text with line breaks in the editor and make it look good

I am a beginner in javascript and I have a problem and I do not know how to put text with many line breaks in addition to putting variables,I know that there is another way that is to put the text and the variables in a stright line but I would like another way,since I have a lot of text and I wish I could read it and modify it to my liking. :)
My question is how can I do this without having to make a straight line in the code?
I would like to have something like this in my code and being able to add variables to it
function procesDATA (LINKS, DATAINF, State, Callback) {
console.log(DATAINF);
console.log(LINKS);
var text = "Lorem ipsum"+ DATAINF.geo + "dolor sit amet, consectetur adipiscing elit."
"Sed hendrerit sapien sit amet mattis facilisis." `+ DATAINF.name +` "Donec dolor mi,
dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum
ante erat.`+ DATAINF.date`";
fs.writeFile(DATAINF.gamename + ".txt", text,"utf-8", function(err) {
let OK = ["Archivo Guardado"]; console.log(OK);
});
}
Thank you very much to those who can help me :)
The new way
Using "Template literals", text will be verbatum in between the `tick` marks -- including new lines and leading tabs:
var text = `Lorem ipsum ${DATAINF.geo} dolor sit amet, consectetur adipiscing elit."
"Sed hendrerit sapien sit amet mattis facilisis." ${DATAINF.name} "Donec dolor mi,
dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum
ante erat. ${DATAINF.date}`;
To integrate varibles wrap them with ${ varible in here }
The old way
While reliable, it's clunky has many caveat's... You have to understand how to wrap quotes and/or escape single/double quotes. (I chose to wrap with single quotes because the text contained many double quotes.)
var newline = "\n"; // if windows maybe use "\r\n"
var text = 'Lorem ipsum ' + DATAINF.geo + ' dolor sit amet, consectetur adipiscing elit. ' + newline;
text += 'Sed hendrerit sapien sit amet mattis facilisis. ' + DATAINF.name + ' Donec dolor mi, ' + newline;
text += 'dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum ' + newline;
text += 'ante erat. ' + DATAINF.date + newline;
Wrap and/or escape quotes
NOTE: Only for the "old way"... you _don't_ have to deal with this if using the "new way"
You can use single quotes to wrap double quotes:
var foo = 'this has a double quote" in here';
Or you can use double quotes to wrap single quotes:
var foo = "this has a single quote' in here";
If you have both single and double quotes, you have to escape the one's that match the wrapper with a backslash:
// since we wrap with double, escape the inner double with a backslash
var foo = "this has \" both in ' here";
// since we wrap with single, escape the inner single with a backslash
var foo = 'this has " both in \' here';
Edit: Unless your question is just about how to format in the editor in which case
just do this.
"The question brown fox " + object.info +
"Jumped over " + object.otherinfo +
"The lazy " + object.extrainfo +
"dog"
i dont know why you have the extra ` in your ideal string.
unless you are talking about formatting the final output content in a file in which case you can just add
\n
where you want new lines.
For more information
var text = `Lorem ipsum ${DATAINF.geo} dolor sit amet, consectetur adipiscing elit.\n Sed hendrerit sapien sit amet mattis facilisis.\n ${DATAINF.name} Donec dolor mi, dapibus nec sollicitudin ut, pulvinar" "eu" "ex. Maecenas nec faucibus turpis. Vestibulum ante erat.\n ${DATAINF.date}`;

How to query for the content inside a h3 tag

I am using the following jQuery code to try to get the text inside the element and add it to my variable:
<script>
var title = $('h3').html();
alert(title);
</script>
However, my browser is alerting me 'undefined' instead of the value inside the tag. Any idea what I am doing wrong?
Here is the html section for reference:
<article>
<div class="row">
<div class="columns large-6 large-centered medium-8 medium-centered small-12">
<h3>This is the post title</h3>
<h4>written by <b>Myself</b></h4>
<section>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla lacinia urna sit amet convallis dictum. Curabitur non sodales orci. Praesent vel gravida felis. Cras ultricies velit mi, eget efficitur ipsum tempus nec.</p>
</section>
</div>
</div>
</article>
Thanks,
This is the solution using plain JavaScript; you don't actually need jQuery here.
var h3element = document.getElementsByTagName("h3")[0];
This returns an array of all h3 elements in the document, of which you'll take the 0th index. Then, simply access the innerHTML property:
var h3content = h3element.innerHTML;
A complete solution would look something like:
<script>
var title = document.getElementsByTagName("h3")[0].innerHTML;
alert(title);
</script>
Try to wait for your document to trigger the ready event, if your code is beyond your tag, for example in the header. And if you only need the text, use the text function in jQuery.
<script>
$(function() {
var title = $('h3').text();
alert(title);
});
</script>
Do something like:
alert(document.getElementsByTagName('h3')[0].innerHTML)

JQuery Toggle With Plus and Minus Icon

I have two sections namely
1. section one
2. section two
I'm performing JQuery slide up and slide down between two div sections with plus and minus sign change..currently it works superbly i want to make one small change in my code when i click on section one contents of section two is hidden and vice versa i need both should be opened simultaneously can somebody help me out in achieving it Thanks!
http://jsfiddle.net/v9Evw/348/
HTML
<ul id="toggle-view">
<li >
<h3 style='background:#4c97d0;color:#fff;'>Section one</h3>
<span style='background:#4c97d0;color:#fff;' class='glyphicon glyphicon-plus'></span>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim.</p>
</li>
<br>
<li>
<h3 style='background:#4c97d0;color:#fff;'>section two</h3>
<span style='background:#4c97d0;color:#fff;' class='glyphicon glyphicon-plus'></span>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim.</p>
</li>
</ul>
JQUERY
var parent = $('#toggle-view'), // storing main ul for use below
delay = 200; // storing delay for easier configuration
// bind the click to all headers
$('li h3, li span', parent).click(function() {
// get the li that this header belongs to
var li = $(this).closest('li');
// check to see if this li is not already being displayed
if (!$('p', li).is(':visible'))
{
// loop on all the li elements
$('li', parent).each(function() {
// slide up the element and set it's marker to '+'
$('p', $(this)).slideUp(delay);
});
// display the current li with a '-' marker
$('p', li).slideDown(delay);
}
else {
$('p', li).slideUp(delay);
}
$('span',li).toggleClass('glyphicon-plus glyphicon-minus');
});
Remove the loop which changes the state on all the content areas. You only want to apply it to the selected content.
So now you are saying; if this is open, close it, otherwise open it.
if (!$('p', li).is(':visible')) {
$('p', li).slideDown(delay);
} else {
$('p', li).slideUp(delay);
}
http://jsfiddle.net/v9Evw/350/
Please find the updated fiddle
http://jsfiddle.net/v9Evw/349/
//$('li', parent).each(function() {
// slide up the element and set it's marker to '+'
$('p', $(this)).slideUp(delay);
// });
Only selected section will slide instead of section 1 and 2. Please see if this meets ur requirement

jquery javascript show/hide toggle remove stuff

I want to remove Phase Content (1st header - See fiddle) and want only these in my code:
Expand - all steps
Steps 1
Steps 2
Steps 3
The above should appear without Phase Content in the code. But i dont know how to change the javascript so as to remove the Phase Content and work only with Steps Content
JSFIDDLE
or below is the code:
jQuery(".phaseContent").hide();
jQuery(".stepsContent").hide();
//toggle the componenet with phase level
jQuery(".phaseHeading .heading1").click(function () {
$(this).toggleClass("active");
var th = jQuery(this).parent();
jQuery(th).next(".phaseContent").slideToggle(500);
return false;
});
jQuery(".stepsHeading .heading1").click(function () {
$(this).toggleClass("active");
var th = jQuery(this).parent();
jQuery(th).next(".stepsContent").slideToggle(500);
return false;
});
//Expand and collapse toggle
$(".accordion-expand-all").click(function () {
var expandLink = $(this);
var contentAreas = $(expandLink).closest(".phaseContent").find(".stepsContent");
// Toggle the content area visibility
$(contentAreas).toggle();
// If the content area is now visible
if ($(contentAreas).is(':visible')) {
// Change it to the collapse text
$(expandLink).text('Collapse - all steps');
} else {
// Change it to the expand text
$(expandLink).text('Expand - all steps');
}
$(expandLink).closest(".phaseContent").find(".stepsHeading .heading1").toggleClass("active");
return false;
});
HTML
<!-- Start Phase -->
<!-- Start phase heading -->
<div class="phaseHeading"><span class="heading1">Phase 1</span>
</div>
<!-- Start phase content -->
<div class="phaseContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis, quam.
<!--Expand steps button-->
<p class="accordion-expand-holder">
<a class="accordion-expand-all" id="st1" href="#">Expand View - all steps</a>
</p>
<!-- Start steps heading -->
<div class="stepsHeading"><span class="heading1">Steps 1</span>
</div>
<div class="stepsContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet.
</div>
<!-- Start step 2 -->
<div class="stepsHeading"><span class="heading1">Steps 2</span>
</div>
<div class="stepsContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis.
</div>
<!-- Start step 2 -->
<div class="stepsHeading"><span class="heading1">Steps 3</span>
</div>
<div class="stepsContent">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis.
</div>
</div>
I update your Fiddle. Please check this jsFiddle
I remove phaseHeading from your HTML and put one Div above accordion-expand-holder name <div class="stepsParent">
<div class="stepsParent">
<p class="accordion-expand-holder"> <a class="accordion-expand-all" id="st1" href="#">Expand View - all steps</a>
</p>
<!-- Start steps heading -->
<div class="stepsHeading"><span class="heading1">Steps 1</span>
</div>
<div class="stepsContent">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet.</div>
<!-- Start step 2 -->
<div class="stepsHeading"><span class="heading1">Steps 2</span>
</div>
<div class="stepsContent">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis.</div>
<!-- Start step 2 -->
<div class="stepsHeading"><span class="heading1">Steps 3</span>
</div>
<div class="stepsContent">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis.</div>
</div>
Also change JS like Below
$(document).ready(function () {
$(".accordion-expand-all").parent().parent().find(".stepsContent").hide("slide");
jQuery(".stepsHeading .heading1").click(function () {
$(this).toggleClass("active");
var th = jQuery(this).parent();
jQuery(th).next(".stepsContent").slideToggle(500);
return false;
});
var collapsed = 1;
$(".accordion-expand-all").click(function () {
var expandLink = $(this);
var contentAreas = $(expandLink).parent().parent().find(".stepsContent");
if (collapsed == 0){
$(contentAreas).hide("slide");
collapsed =1;
$(expandLink).text('Expand - all steps');
} else {
$(contentAreas).show("slide");
collapsed = 0;
$(expandLink).text('Collapse - all steps');
}
$(expandLink).closest(".stepsHeading .heading1").toggleClass("active");
return false;
});
});
i have updated your jsFiddle, hope you get your solution.
changed javascript part
jQuery(".phaseHeading .heading1").click(function () {
$(this).toggleClass("active");
var th = jQuery(this).parent();
jQuery(th).next(".phaseContent").slideToggle(500);
jQuery(".phaseContent1").hide();
jQuery(".phaseHeading").hide();
return false;
});
changed html part
<div class="phaseContent1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet, nunc eget laoreet sagittis, quam.
</div>
or you can also remove this changed div from html and jQuery(".phaseContent1").hide(); from changed js
You can use this
$(".phaseHeading .heading1").click(function () {
$(this).toggleClass("active");
var th = jQuery(this).parent();
$(th).next(".phaseContent").slideToggle(500);
$(".phaseContent1").hide();
$(".phaseHeading").hide();
return false;
});
Also do some changes in Div Class
<div class="Content1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum laoreet.
</div>

Search iframe content with jquery and input element on parent page

I was wondering how I can have a text input element on the parent page which searches the content of an Iframe within the parent page.
The goal is to have the input text processed and to highlight the matches within the iframe.
Any suggested approaches or references would be appreciated.
Thanks...
EDIT: I understand the limitations on the same origin policy, The parent page rendering the iframe and javascript to search, as well as the iframe on the parent page would be of the same domain origin.
HTML:
<input type="text" id="searchfor"/>
<iframe src="http://www.page.com" id="search">Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euism modo typi, qui nunc nobis videntur parum clari, fiant sollemnes in futurum.
Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tinci futurum.</iframe>
JAVASCRIPT:
$('#searchfor').keyup(function(){
var page = $('iframe[id="search"]').contents().find("html").html();
var pageText = page.text().replace("<span>","").replace("</span>");
var searchedText = $('#searchfor').val();
console.log(searchedText);
var theRegEx = new RegExp("("+searchedText+")", "igm");
var newHtml = pageText.replace(theRegEx ,"<span>$1</span>");
page.html(newHtml);
});

Categories

Resources