I have a recipe containing a ul
containing li
Separate recipe content for page I am trying to get those elements and trying to store them in a JavaScript array within an object. I already know the title of the recipe, so I put that object property in title
, but I do not know how many elements are there for each recipe. Val (), content: [ingredient, optional]} $ .eee ($ ('Ul.ingitals'> li>, h4'), function (index, element) {recipeobj.ingredients [index] .ingredient = $ (Component). Html (); recipeobj.ingredients [index]. Optional = false;})
If I try to console.log (recipeobj.ingredients) I get the error
Uncaught ReferenceError: The component is not defined
There is no doubt that it is simple, I have to use arrays rarely in javascript So that Have a little experience with
open your console and run it
< Div class = "snippet" data-lang = "js" data-hide = "wrong">
var recipeobj = {title: $ ('h3.title'). Html (), // content is now empty for the ingredients: []}; $ .each ($ ('ul.ingredients & gt; li & gt; h4'), function (index, component) {// name var name = $ (component) .html (), // find out what this Paste a new component in 'Optional' (use square here) optional = $ (component) .hasClass ('optional'); // array at recipeobj.ingredients.push ({name, optional: optional}) ;}); Console.log (recipeobj);
& lt; Script src = "https: //ajax.googleapis com / ajax / libs / jquery / 2.1.1 / jquery.min.js" & gt; & Lt; / Script & gt; & Lt; H3 class = "title" & gt; Pork and beans & lt; / H3 & gt; & Lt; Ul class = "content" & gt; & Lt; Li & gt; & Lt; H4 & gt; Pork & lt; / H4 & gt; & Lt; / Li & gt; & Lt; Li & gt; & Lt; H4 & gt; Beans & lt; / H4 & gt; & Lt; / Li & gt; & Lt; Li & gt; & Lt; H4 square = "optional" & gt; Salt * & lt; / H4 & gt; & Lt; / Li & gt; & Lt; / Ul & gt; This output should be: <">" title ":" pork "and" name ":
No comments:
Post a Comment