Using Cheerio Js to select a particular element with same class - javascript

<div class='one'>THis is first div</div>
<div class='one'>THis is the second div</div>
So I want to get the text inside these two divs one by one. So with each loop it only gets the current element of the div.
const searchResult = selector("div[class='one']")
.each((index, element) => {
let selection = selector(element);
return selection.text();
})
.get(index);
So with each div with class="one", I want to return the text of that div only, above is my current code, but it doesn't seem to work, it seems that the .get() isn't right.

I think you want map:
$(div.one).map((i, div) => $(div).text()).get()

Related

Perform append operations without using the id element in java script

I want to see if there is a way to define the second div without defining an ID for the element or without using an attribute, and perform the append operation inside it, for example, to say that the p element should be appended inside the second div without using id And any other attribute, let's mention the second div.
More details are in the code *
function createEle() {
var c = document.createElement('p');
// In this section, I want to point to that div and use append without using an ID or any other attribute
return ?
}
createEle();
<section>
<div>
<div>I want the p tag to be appended in this div</div>
</div>
</section>
You can use a selector string instead, with only tag names. Eg section > div > div will select the nested div (it'll select a div which is a child of a div, which is a child of a section):
function createEle() {
const inner = document.querySelector('section > div > div');
inner.appendChild(document.createElement('p')).textContent = 'foo';
}
createEle();
<section>
<div>
<div>I want the p tag to be appended in this div</div>
</div>
</section>

Detect click on text part of a block element

I have the following html element:
<h1>Some text</h1>
I need to detect a click and recognize whether it landed on the text part or the blank part of the element.
To preserve consistency of the rest of the app I cannot change the display of this element to inline or inline-block.
I also cannot modify the inner html of this element so splitting it into two <span> elements is not an option either.
The text inside this element is not constant and is in fact editable.
Can I detect a click only on the visible (text) part of this heading?
QUESTION "I also cannot modify the inner html of this element so splitting it into two elements is not an option either." does this mean after the fact or before the fact? i.e is it that you cannot alter the HTML or that you can't go in and mutate the HTML via JS ?
Current Solution:
I parse all elements with the .clickable identifier, remove & rebuild their text contents and place spans around them - this way i can add click listeners to the individual text/span elements - giving me access to the text itself.
const clickables = document.querySelectorAll('.clickable')
clickables.forEach(el => new Clickable(el))
function Clickable (el) {
const _handleClick = ({target}) => console.log(target.innerHTML)
const texts = el.textContent.split(/\s/)
el.innerHTML = ''
texts.forEach(t => {
const span = document.createElement('span')
span.innerHTML = `${t} `
span.addEventListener('click', _handleClick)
el.appendChild(span)
})
}
<h1 class="clickable">Some text</h1>
<h2 class="clickable">Some! more! text2</h1>
By the use of Jquery you can use the .click function to know if the h1 tag is clicked.
$('#test').click(function(){
alert("Clicked!");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h1 id='test'>TEST</h1>

How to find earlier element by partial id

I trying to find the parent div of a clicked item but can only get it working by manually setting the div id. There are many similar divs with incrementing id's
<div id="grid0"...
<div id="grid1"...
<div id="grid2"...
etc
My javscript is as follows but this only finds the first grid
function popUp1HtmlContent(e) {
var dataItem = $("div[id^=grid]").data("kGrid").dataItem(e.target.closest("tr"));
var content = dataItem.PopUp1Html;
return content;
}
How do I find the parent div in this function?
Eg setting this manually works for each grid
var dataItem = $("div[id=grid0]").data("kGrid").dataItem(e.target.closest("tr"));
var dataItem = $("div[id=grid1]").data("kGrid").dataItem(e.target.closest("tr"));
etc
Is there a way to search back through the parents to find the first matching div with id starting "grid{0}"?
The event fires from an image within a td element. Also it's not always the direct parent but can have varying number of elements between clicked element and div I'm trying to locate.

How to swap placement of two elements, including their classes/ids with onclick?

I'm trying to switch the positions of two divs with an onclick event.
The divs have the same basic format (width, height), but an additional class and id change the way they look.
So, I have two functions that successfully change the id and class names, but there is no visual change.
Here they are:
function whenClickedFilled(){
console.log("filled");
this.firstElementChild.id = "empty";
this.firstElementChild.className = "puzzlepiece emptyDivClass";
}
function whenClickedEmpty(){
console.log("empty");
this.firstElementChild.id = "filled";
this.firstElementChild.className = "puzzlepiece";
}
I'd like to know what the best way is to alternate between classes/ids onclick.
Here is my js fiddle.
I think what you're really looking to do is not swaping the class and id, but swap the elements themselves. This will make sure the numbers contained within the div's is also transfer with the swap.
You still need to implement the logic checks to see if the element should be able to swap with the empty block and there looks like theres a bug when you click empty space itself. But, this should get you on the right track. I recommend placing a debugger statement to step through the code with dev tools open. It will help understand whats taking place. Good luck.
function whenClickedFilled(){
console.log("filled");
//Get the div element and parent
//Then determine the parent of the empty div
var clickedDiv = this.firstChild; //this refers to the TD clicked, get the child div element
var clickedDivParent = this; //this is TD
var emptyDivParent = emptyDiv.parentElement; //stored the empty div reference into a global, retrieve the parent as this could change
//Remove the empty and clicked div's from their container
emptyDivParent.removeChild(emptyDiv)
clickedDivParent.removeChild(clickedDiv);
//Add the elements back to the containers but swapped
clickedDivParent.appendChild(emptyDiv);
emptyDivParent.appendChild(clickedDiv);
}
http://jsfiddle.net/tWrD2/
I'm trying to switch the positions of two divs with an onclick event
If you want to swap two adjacent nodes, you can do something as simple as:
function swapAdjacent(el0, el1) {
el0.parentNode.insertBefore(el1, el0);
}
If you want to swap any two elements in the DOM, you can do something like:
// Swap the postion in the DOM of el0 and el1
function swapElements(el0, el1) {
// Create a temp node that can replace el0
var tmp = el0.cloneNode(false);
// Replace el0 with tmp
el0.parentNode.replaceChild(tmp, el0);
// Replace el1 with el0
el1.parentNode.replaceChild(el0, el1);
// Replace temp node with el1
tmp.parentNode.replaceChild(el1, tmp);
}
and some test markup:
<div id="d0">div 0</div>
<div id="d1">div 1</div>
<button onclick="
swapElements(document.getElementById('d0'), document.getElementById('d1'));
">Swap d0, d1</button>
<button onclick="
swapAdjacent(document.getElementById('d0'), document.getElementById('d1'));
">Swap adjacent</button>
Of course the two elements to swap must be consistent with the surrounding elements, e.g. you can't swap an option element with a div and expect everything to work, but you can probably swap a span with a div.
If you want to swap elements by clicking on one or the other:
<div id="d0" onclick="swapElements(this, document.getElementById('d1'))">div 0</div>
<div id="d1" onclick="swapElements(this, document.getElementById('d0'))">div 1</div>
I found a nice solution provided by fuell when I was searching fo an actual html swap:
<div id="div_1">THIS IS DIV 1</div>
<div id="div_2">THIS IS DIV 2</div>
Go Swap!
$(document).ready(function() {
$(".go-swap").click(function() {
$("#div_1").removeAttr("style");
$("#div_2").removeAttr("style");
var tmp = $("#div_1").html();
$("#div_1").empty().append($("#div_2").html());
$("#div_2").empty().append(tmp);
});
});

jquery .each() loop

i want to read all links in ".vm-video-title"-divs and post them each in the same div. So i made this script:
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("div.vm-video-title>a").text());//add to div the link
});
but i have the problem that it reads ALL the links of all divs and put them in one div.
example:
<div class="vm-video-title">Text1</div>
<div class="vm-video-title">Text2</div>
<div class="vm-video-title">Text3</div>
output:
Text1Text1Text2Text3
Text2Text1Text2Text3
Text3Text1Text2Text3
wanted output:
Text1Text1
Text2Text2
Text3Text3
You can select the <a> elements directly, and use the after()[docs] method to append the content of each after each one respectively.
$("div.vm-video-title > a").after(function() { return $(this).text(); });
This doesn't do a "destroy then recreate" of the existing elements like the html()[docs] method will.
Working example: http://jsfiddle.net/CCr9C/
This should do the job for you,
you need to find the div inside current element in the loop (el).
$('.vm-video-title').each(function(i, el) {
el = $(el);
el.html(el.html()+el.find("a").text());
});
in your code you are adding text() of all matching "a" tags in your divs (i.e. Text1Text2Text3)
You were almost there. Instead of : $("div.vm-video-title").text(), which gives you text inside any div with class vm-video-title, you need to find a tag inside current div and get text from it. We pass this as context for selecting a inside current div jQuery( selector, [context] )
$('.vm-video-title').each(function(i) {//all divs
$(this).html($(this).html()+$("a", this).text());
});

Categories

Resources