Style output of an jQuery array - javascript

I have an array containing a number of statements/quotes but I would like to add some custom HTML to help style each quote when they are displayed.
In the below code I have demonstrated what I'd like to do but at the moment the actual HTML tags are output as strings. How do I get them to render as HTML so I can style them with CSS?
Here's a working fiddle showing what I mean: https://jsfiddle.net/tawasnng/1/
// Random testimonials headlines = new Array('Food was amazing and the drinks well-priced. We’ll be back soon!<span class="boom">Test</span>', "Bad", "Ugly", "Random Headline"); var randomNumberBefore = 4;
function randomNumberByRange (range, number) {
var r = Math.floor(Math.random() * (range-1));
if(r >= number)r++;
return r; }
$(document).on('click','.nextquote' , function() {
var randomNumber = randomNumberByRange( headlines.length, randomNumberBefore);
randomNumberBefore = randomNumber;
var nextHeadline = headlines[randomNumber];
$(".quote").text(nextHeadline);
});

You need to use .html() instead of .text() in order to make it output as HTML. Replace the following:
$(".quote").text(nextHeadline);
With:
$(".quote").html('<span class="headline">' + nextHeadline + '</span>');
And try giving something for the .headline class!

Related

how to replace class name dynamically in javascript

I want to change a class dynamically and append a counter to the end of it. I wrote this code but it is treated like strings.
This is the code:
var divClass = document.getElementById('div2');
var i = 1;
setInterval(function () {
divClass.className=divClass.className.replace('color','color'+ i);
i++;
},5000);
how can i fix this issue?
I think the issue is that after the first loop the class name will be color1 and your replacing only the "color" part so you end up with color12 You could just set className since that overrides the previous one
divClass.className = 'color'+ i;
if you had classes before you can store them and them first so you don't override them : var classes = divClass.className;
and when you set them divClass.className = classes + ', color'+ i;
You could use the classList feature that is in JavaScript like this:
var divClass = document.getElementById('div2');
var i = 1;
setInterval(function () {
divClass.classList.remove('color' + (i - 1));
divClass.classList.add('color' + i++);
}, 5000);
Your numbers are more than likely getting treated as a string because you are concatenating with a string. By placing items within parentheses, they will be executed as numbers (because anything in parentheses get run first) then concatenated as a string.
Use instead:
element.className = 'other const clases' + 'color'+ i;
You have to change full string of class or change it in 2 steps with for example regex and then assign it again.

How can I get the locator value from a webelement?

I would like to get the value of the selector used from a selenium webelement in javascript.
If I have the object:
var el = browser.driver.findElement(by.id('testEl'));
I'd like to get that text 'testEl' and use it elsewhere. I don't care what the selector type is(by id, by css, etc.), just what the text is.
In protractor, I could do this:
console.log(el.locator().value);
This would return the text 'testEl'.
But with just selenium non-protractor selectors, I am told that .value() is not a function.
Is there any way to pull this locator/selector value out?
EDIT:
The goal: Grab the locator text from a selenium webElement
The use: For functions like getVisibleElement
The situation: Working against a page where there can be an unknown number of elements of a certain selector, some hidden and some not(but an area above them hidden, no hidden tag on this particular portion of the element to work with), and I'd like to get just the visible ones.
In protractor:
function getVisibleElementByPageObject(protractorWebElement){
var allElementsOfSelector = element.all(by.css(protractorWebElement.locator().value));
var displayedElement = allElementsOfSelector .filter(function(elem) {
return elem.isDisplayed('cannot find' + ' ' + protractorWebElement.locator().value);
}).first();
return displayedElement ;
}
var exampleEl = $('[name="test"]');
var visibleExampleEl = getVisibleElementByPageObject(exampleEl);
I'd like to get the locator so that if I ever change what the selector is, I would need to only change it in one place - the page object where the element is declared.
I can use a var to store the string and pass that along anytime I declare an element or try to use something like the above, but that just means using a new standard of setting up page objects. It would be very convenient to access the locator in selenium like protractor does above.
You don't need to get the locator from the webElement, you should already have it the first time you use it to find the element. If your page objects aren't already set up that way, you're doing it wrong.
In webdriver.js, they show this example:
* var link = element.findElement(firstVisibleLink);
*
* function firstVisibleLink(element) {
* var links = element.findElements(By.tagName('a'));
* return webdriver.promise.filter(links, function(link) {
* return links.isDisplayed();
* }).then(function(visibleLinks) {
* return visibleLinks[0];
* });
* }
So you should be able to:
var firstElement = function(locator) {
return browser.driver.findElement(locator);
};
var firstVisible = function(locator) {
var elements = browser.driver.findElements(locator);
return browser.driver.promise.filter(elements, function(el) {
return el.isDisplayed();
}).then(function(visibleElements) {
return visibleElements[0];
});
};
var testLocator = by.css('[name="test"]');
var E1 = firstElement(testLocator);
var E1v = firstVisible(testLocator);

Select Part of a Attribute - JQuery

I need to get the number only from an attribute (The number is dynamic). The button/anchor looks like this:
Delete Dish
The part I need to dissect is this bit 'bc_inventorybundle_menu_product_0' I only want the number, for use in another function (Delete a LI with an ID of menuitem0_dish)
The code I use for selecting ID's elsewhere is:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("id").substring((prefix.length));
return num;
}
It works great on ID's but I cant seem to get it to work for Attributes instead of ID's
So User clicks delete button bc_inventorybundle_menu_product_0 then jQuery removes the < li id="menuitem0_dish">
I can't add an ID to the button so I have to use the attribute of the button. As I'm sure you can tell I'm a complete noob when it comes to JS/JQuery.
EDIT
Having read all the answers I feel I may need to elaborate a little.
I think the biggest issue is registering when the Button/Anchor is clicked.
What I currently have is this, which I know must be wrong:
$(document).on('click', 'data("field")', function(event) {
deleteDish(this);
});
function getbutNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var butnum = element.data("field").substring(prefix.length); //Changed as per suggestions
return butnum;
}
function deleteDish(field) {
var numbut = getbutNum();
//Delete the UL/LI
console.log("Num But" + numbut);
}
Asides from all else this gives me an error of 'unrecognized expression: data("field")'
Have you tried selecting your actual data attribute:
var num = element.attr("data-field").substring(prefix.length);
Or:
var num = element.data("field").substring(prefix.length);
EDIT
First add a class to your anchor element (I'm going under the assumption that you have more than one of these):
Delete Dish
Then:
$(".delete-dish").on("click", function (e) {
e.preventDefault();
var fieldData = $(this).data("field"),
num = fieldData.substring(fieldData.lastIndexOf("_") + 1);
console.log("Num But" + num);
});
Here is a fiddle to demonstrate
Using the attribute name that contains your input should work:
function getNum(element, attrPrefix) {
//set prefix, get number
var prefix = attrPrefix;
var num = element.attr("data-field").substring((prefix.length));
return num;
}
http://jsfiddle.net/zf3hmo4q/
Considering you want to parse attributes with "data-*" name:
function getNum(element, dataName, dataPrefix) {
var num = element.data(dataName).replace(dataPrefix, "");
return num;
}
console.log(getNum($(".btn"), "field", "bc_inventorybundle_menu_product_"));
Maybe something like this?
var getNumberFromAttribute = function(id, field) {
var field = $(id).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
Here's a jsfiddle http://jsfiddle.net/o6go79cL/
UPDATE
You could just pass in the element. The only purpose of the id was to select the object. So you could also just do:
var getNumberFromAttribute = function(elm, field) {
var field = $(elm).data(field);
var parts = field.split("_");
return parts[parts.length - 1]
}
number = getNumberFromAttribute(anchorTag, "field");

function to change argument to another sign

I dynamically create this list element and information a user has typed in shows up in it when a button is clicked 'info' is text and shuld show as it is but 'grade' is a number that i want to convert to another sign with the function changeNumber() but I am new to javascript and cant figure out how to make this function, can anyone give a suggestion or point me in the right direction?
var list = $("#filmlista");
var list_array = new Array();
function updateFilmList()
{
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = list_array[0][1];
var element = '<li class="lista">' + list + '<span class="grade">'+ changeNumber(grade) +'</span></li>';
list.append(element);
}
should I use innerHTML? not shure I understand how it works? and how do I use the replace method if I have to replace many different numbers to the amount of signs the number is?
for example if the number is 5 it should show up as: *****, if number is 3 show up as: *** and so on
Here's some code that should do the trick:
Add this function into your script.
function changeNumber(number) {
var finalProduct = "";
for (var i = 0; i < number; i++) {
finalProduct += "*";
}
return finalProduct;
}
Replace the updateFilmsList with this code.
document.getElementById("name").value = '';
document.getElementById("star").value = 0;
var listan = list_array[0][0];
var grade = changeNumber(list_array[0][1]);
var element = '<li class="lista">' + list + '<span class="grade">'+ grade +'</span></li>';
list.append(element);
It looks like you're trying to do something like PHP's str_repeat. In that case, take a look at str_repeat from PHPJS
There are options other than a loop:
function charString(n, c) {
n = n? ++n : 0;
return new Array(n).join(c);
}
charString(3, '*'); // ***
You can use innerHTML to set the text content of an element provided none of the text might be mistaken for markup. Otherwise, set the textContent (W3C compliant) or innerText (IE proprietary but widely implemented) property as appropriate.

DOM element not being found after cloning and appending unique ID

So I'm creating a random string value:
var randomString = function(stringLength) {
var i = 0;
stringLength = stringLength || 10;
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var randomString = '';
for (i = 0; i < stringLength; i += 1) {
var rNum = Math.floor(Math.random() * chars.length);
randomString += chars.substring(rNum, rNum + 1);
}
return randomString;
};
And associating it with a list element on one pane:
var addUniqueId = function($thumbnail) {
var random = randomString(10);
$thumbnail.attr('id', 'rand-' + random);
};
And then cloning it and moving that list element to the right:
var cloneImage = function($thumbnail) {
addUniqueId($thumbnail);
var $lastImgAdded = $('.js-gallery-edit-pane li').last();
var span = $('<span />');
span.addClass('x').text('x');
var $clone = $thumbnail.clone(true, true).appendTo($('.js-gallery-edit-pane')).prepend(span).hide().fadeIn(200).unbind('click');
bindRemoveHandler($clone);
};
Then I add an overlay to the list element on the left to "gray" it out. Everything works at this point.
From there, a user can remove the recently cloned items on the right hand side by clicking the "X" on the image. This works fine and removes that recently cloned image, however, the original overlay is not being found. It should be associated with the random string value, so I'm just looking for that in $('.js-gallery-select-pane').find('#rand-' + string).find('.overlay').remove(); but for some reason it's not finding it...
Any idea why?
JSFiddle Demo
If you put an alert(string) in your code, you will see that the string already includes rand- so in your selector just do:
$('.js-gallery-select-pane').find('#' + string).find('.overlay').remove();
Here is the working JSFiddle
You have two collections of elements with ID pairs in them.
There's three problems though. The first two problems problem are here..
You were taking the complete id of the clone 'rand-etctcetc'
then adding rand- to it again 'rand-rand-etcetcetc' then using it as a selector. $('rand-rand-etcetcetc'). Instead I changed it to just add the neccessary # to the id. You also need to remove the js-gallery-editing class in order to let you add things back to the list on right hand side.
var bindRemoveHandler = function($thumbnail) {
$thumbnail.on('click', function() {
$(this).fadeOut(200, function() {
var string = $(this).attr('id');
$('.js-gallery-select-pane').find('#' + string).removeClass('js-gallery-editing').find('.overlay').remove();
$(this).remove();
updatePictureCount();
});
});
};
You could stop here but, you also have a different problem. The ID attribute is intended to be unique. Try using a custom attribute and the Jquery attribute equals selector. The query you want would look something like this..
$('.js-gallery-select-pane').find('[pairid="' + string +'"]');
Here, have a fiddle: http://jsfiddle.net/s3dCB/

Categories

Resources